package com.gsit.ocrbatch.services;

import static com.gsit.ocrbatch.utils.FileConstant.FILE_OUT_PATH;
import static com.gsit.ocrbatch.utils.FileConstant.FILE_PROCESSED_PATH;
import static com.gsit.ocrbatch.utils.FileConstant.FILE_IN_PATH;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.gsit.ocrbatch.domain.Record;

@Repository
public class OcrFileWriter {
	
	public void write(List<Record> records)throws IOException{
		
		for (Record record : records) {
			File source = new File(FILE_IN_PATH+"/"+record.getName());
			File target = new File(FILE_PROCESSED_PATH);
			copyFile(source, target);
			
			if(source.isFile()){
				source.delete();
			}
			
		}
		
	}
	
	
	private static void copyFile(File source, File target) {
	    try (InputStream fis = new FileInputStream(source);
	        OutputStream fos = new FileOutputStream(target)){
	 
	        byte[] buf = new byte[8192];
	 
	        int i;
	        while ((i = fis.read(buf)) != -1) {
	            fos.write(buf, 0, i);
	        }
	    }
	    catch (Exception e) {
	        e.printStackTrace();
	    }
	}

}
